package org.lex.jdbc;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.lex.jdbc.util.DriverUtils;

public class Temp {
	public static void main(String[] args) throws Exception {
		driversTest();
		connectMySQL();
		testOdbc();
	}

	static void testOdbc() throws Exception {
		String url = "jdbc:odbc:test";
		Connection con = MyDriverManager.getConnection(url);
		printConn(con);
	}

	static void connectMySQL() throws Exception {
		String url = "jdbc:mysql://localhost/test";
		Enumeration<Driver> e = MyDriverManager.getDrivers();
		while (e.hasMoreElements()) {
			System.out.println("++Driver: " + e.nextElement());
		}
		Connection conn = MyDriverManager.getConnection(url, "root", "root");
		printConn(conn);
	}

	static void printConn(Connection conn) throws Exception {
		DatabaseMetaData md = conn.getMetaData();
		System.out.println(md.getDatabaseProductName() + " - " + md.getDatabaseProductVersion());
		conn.close();
	}

	static void driversTest() throws Exception {
		String path = "C:\\_liuex\\lib\\jdbc";
		List<Class<?>> list = new ArrayList<Class<?>>();
		DriverUtils.loadDrivers(list, new File(path));
	}

	static void log4jTest() throws Exception {
		String path = "C:\\_liuex\\workspaces\\test\\test\\lib\\log4j-1.2.15.jar";
		File file = new File(path);
		System.out.println(file + " exists? " + file.exists());

		URL url = file.toURI().toURL();

		ClassLoader loader = URLClassLoader.newInstance(new URL[] { url }, Temp.class.getClassLoader());
		Class<?> clz = Class.forName("org.apache.log4j.Logger", true, loader);
		System.out.println("load: " + clz);

		Method getLoggerM = clz.getMethod("getLogger", String.class);
		Method logM = clz.getMethod("info", Object.class);

		Object log = getLoggerM.invoke(null, "test.Temp");
		logM.invoke(log, "logging using reflect");
	}

	static void log4jTest2() throws Exception {
		String path = "C:\\_liuex\\lib\\jdbc\\mysql\\mysql-connector-java-5.1.7-bin.jar";
		addClassPath(path);

		// findDriver(new File(path));

		Class<?> clz = Class.forName("com.mysql.jdbc.Buffer");
		System.out.println("load: " + clz);

		// Method getLoggerM = clz.getMethod("getLogger", String.class);
		// Method logM = clz.getMethod("info", Object.class);
		//
		// Object log = getLoggerM.invoke(null, "test.Temp");
		// logM.invoke(log, "logging using reflect");

	}

	static void addClassPath(String jar) {
		String CP = "java.class.path";
		String SEP = "path.separator";
		String cp = System.getProperty(CP);
		cp = cp + System.getProperty(SEP) + jar;
		System.setProperty(CP, cp);
		System.out.println(CP + "=" + System.getProperty(CP));
	}
}
